package com.zjitc.pigstudy.controller;

import cn.hutool.core.io.FileUtil;
import com.zjitc.pigstudy.common.AuthAccess;
import com.zjitc.pigstudy.common.Result;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;

@CrossOrigin
@RestController
@RequestMapping("/file")
public class FileController {

    @Value("${ip}")
    String ip;

    @Value("${port}")
    String port;

    private static final String ROOT_PATH = System.getProperty("user.dir")+File.separator+"files";


    @AuthAccess
    @PostMapping("/upload")
    public Result upload(MultipartFile file) throws IOException {
        String originalFileName = file.getOriginalFilename(); //文件的原始名称
        String mainName = FileUtil.mainName(originalFileName); //不带后缀的文件名
        String extName = FileUtil.extName(originalFileName); //文件的后缀名
        if(!FileUtil.exist(ROOT_PATH)) {
            FileUtil.mkdir(ROOT_PATH); //如果当前文件的父级目录不存在，就创建
        }
        if(FileUtil.exist(ROOT_PATH+File.separator+originalFileName)){  //如果当前上传的文件已经存在了，那么这个时候我就要重命名一个文件名称
            originalFileName = System.currentTimeMillis()+"_"+mainName+"."+extName;
        }
        File saveFile = new File(ROOT_PATH+File.separator+originalFileName);
        file.transferTo(saveFile);  //存储文件到本地磁盘
        String url = "http://"+ip+":"+port+"/file/download/"+originalFileName;
        return Result.success(url); //返回文件的链接，这个链接是文件的下载地址，这个下载地址就是我后台提供出来的
    }

    @AuthAccess
    @GetMapping("/download/{fileName}")
    public void download(@PathVariable String fileName, HttpServletResponse response) throws IOException {

        String filePath = ROOT_PATH+File.separator+fileName;
        if(!FileUtil.exist(filePath)){
            return;
        }
        byte[] bytes = FileUtil.readBytes(filePath);
        ServletOutputStream outputStream = response.getOutputStream();
        outputStream.write(bytes);     //数组是一个字节数组，也就是文件的字节流数组
        outputStream.flush();
        outputStream.close();

    }
}
